from django.db.models import Q
from django.shortcuts import render
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from message import models, ser
from django.core.cache import cache
from django.utils import timezone

# Create your views here.


class MyPagination(PageNumberPagination):
    page_size = 1
    page_size_query_param = 'size'
    page_query_param = 'page'
    max_page_size = 10


class CategoryViewSet(ModelViewSet):
    queryset = models.Cate.objects.all()
    serializer_class = ser.CategorySerializer
    lookup_field = 'pk'
    lookup_url_kwarg = 'pk'


class MessageViewSet(ModelViewSet):
    queryset = models.Message.objects.all()
    serializer_class = ser.MessageSerializer
    lookup_field = 'pk'
    lookup_url_kwarg = 'pk'
    pagination_class = MyPagination

    def get_queryset(self):
        queryset = super().get_queryset()
        title = self.request.query_params.get('title')
        cate = self.request.query_params.get('cate')
        query = Q()
        if title:
            query &= Q(title__icontains=title)
        if cate:
            query &= Q(cate=cate)
        return queryset.filter(query)

    # 将删除 的 痕迹记录到缓存中  可以查看 删除文章的缓存
    @action(methods=['delete'], detail=True)
    def delete_message(self, request, pk):
        message = self.get_object()
        delete_info = {
            'id': message.id,
            'title': message.title,
            'delete_at': timezone.now()
        }
        deleted_list = cache.get('deleted_list', [])
        deleted_list.append(delete_info)
        cache.set('deleted_list', deleted_list, 60 * 60 * 24)
        message.delete()
        return Response(status=status.HTTP_200_OK)

    # 状态
    @action(methods=['get'], detail=True)
    def status(self, request, pk):
        message = self.get_object()
        message.status = not message.status
        message.save()
        return Response(status=status.HTTP_200_OK)


